package interview.juc;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: zhangrongqing
 * @Date: 2019/11/28 15:14
 */
public class ProducerAndConsumer {
    private int count = 0;

    public void consumer() throws InterruptedException {
        synchronized (this) {
            System.out.println("等待");
            this.wait();//wait方法解锁等待
            System.out.println(this.count);
        }
    }

    public void producer() throws InterruptedException {
        synchronized (this) {
            System.out.println("开始生产了");
            Thread.sleep(1000);
            for (int i = 0; i < 100; i++) {
                count += i;
            }
            this.notifyAll();    //notifyAll通知所有wait的线程开始工作
        }
    }


    public static void main(String[] args) {
        ProducerAndConsumer pcTest = new ProducerAndConsumer();
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(() -> {
            try {
                pcTest.consumer();
            } catch (InterruptedException e) {
            }
        });
        executor.execute(() -> {
            try {
                pcTest.producer();
            } catch (InterruptedException e) {
            }
        });
        executor.shutdown();
    }
}